package com.uzai.console.service.wechatprivate.impl;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanPluginIdDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanPluginUpdateDto;
import com.uzai.console.dto.wechatprivate.wxq.manageplan.WxqGroupManagePlanQuery;
import com.uzai.console.dto.wechatprivate.wxq.manageplan.WxqManagePlanDto;
import com.uzai.console.dto.wechatprivate.wxq.manageplan.WxqManagePlanIdDto;
import com.uzai.console.dto.wechatprivate.wxq.manageplan.WxqManagePlanQuery;
import com.uzai.console.dto.wechatprivate.wxq.wxgroup.WxGroupQuery;
import com.uzai.console.entity.ConfigPlan;
import com.uzai.console.entity.SysPlugin;
import com.uzai.console.entity.WxqGroupManagePlan;
import com.uzai.console.entity.WxqManagePlan;
import com.uzai.console.jsonvo.wxq.BaseSet;
import com.uzai.console.mapper.ConfigPlanMapper;
import com.uzai.console.mapper.SysPluginMapper;
import com.uzai.console.mapper.WxqGroupManagePlanMapper;
import com.uzai.console.mapper.WxqManagePlanMapper;
import com.uzai.console.service.wechatprivate.WxGroupService;
import com.uzai.console.service.wechatprivate.WxqManagePlanService;
import com.uzai.console.vo.sysplugin.SysPluginVo;
import com.uzai.console.vo.wechatprivate.wxq.manageplan.WxqManagePlanVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroup.WxGroupInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WxqManagePlanServiceImpl implements WxqManagePlanService {

    @Autowired
    private WxqManagePlanMapper wxqManagePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private WxGroupService wxGroupService;

    /**
     * 查询所有微信群管理方案列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param query
     * @return null
     */
    public List<WxqManagePlanVo> findWxqManagePlanList(WxqManagePlanQuery query){
        //新建返回微信群管理方案下拉列表
        ArrayList<WxqManagePlanVo>  selectList = new ArrayList<>();
        //查询数据库中的微信群管理方案
        ArrayList<WxqManagePlan> wxqManagePlanList = wxqManagePlanMapper.findByList(query);
        if(wxqManagePlanList != null && wxqManagePlanList.size() > 0){
            for (WxqManagePlan wxqManagePlan : wxqManagePlanList){
                WxqManagePlanVo wxqManagePlanVo = new WxqManagePlanVo();
                BeanUtils.copyProperties(wxqManagePlan, wxqManagePlanVo);
                BaseSet baseSet = JSONObject.parseObject(wxqManagePlan.getBaseSet(), BaseSet.class);
                if(baseSet == null){
                    baseSet = new BaseSet();
                }
                wxqManagePlanVo.setBaseSet(baseSet);
                selectList.add(wxqManagePlanVo);
            }
        }
        return selectList;
    }

    /**
     * 查询微信群管理方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqManagePlanIdDto
     * @return null
     */
    public WxqManagePlanVo findWxqManagePlanInfo(WxqManagePlanIdDto wxqManagePlanIdDto){
        if(wxqManagePlanIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //查询微信群管理方案信息
        WxqManagePlan wxqManagePlan = wxqManagePlanMapper.selectById(wxqManagePlanIdDto.getId(), wxqManagePlanIdDto.getMerId());
        if(wxqManagePlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群管理方案不存在");
        }
        //返回页面列表
        WxqManagePlanVo wxqManagePlanVo = new WxqManagePlanVo();
        //对象复制
        BeanUtils.copyProperties(wxqManagePlan, wxqManagePlanVo);
        BaseSet baseSet = JSONObject.parseObject(wxqManagePlan.getBaseSet(), BaseSet.class);
        if(baseSet == null){
            baseSet = new BaseSet();
        }
        wxqManagePlanVo.setBaseSet(baseSet);
        return wxqManagePlanVo;
    }


    /**
     * 添加微信群管理方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqManagePlanDto
     * @return null
     */
    public Long addWxqManagePlan(WxqManagePlanDto wxqManagePlanDto){

        if(wxqManagePlanDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先登录系统");
        }

        if(StringUtils.isBlank(Tools.getStr(wxqManagePlanDto.getName()))){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称不能为空");
        }

        //验证名称重复
        WxqManagePlan wxqManagePlan_name = wxqManagePlanMapper.selectByNameAndMerId(wxqManagePlanDto.getName(), wxqManagePlanDto.getMerId());
        if(wxqManagePlan_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
        }

        Integer now = DateUtil.getNowTime();
        WxqManagePlan wxqManagePlan = new WxqManagePlan();
        Long id = IdWorker.getId();
        wxqManagePlan.setId(id);
        wxqManagePlan.setMerId(wxqManagePlanDto.getMerId());
        wxqManagePlan.setName(wxqManagePlanDto.getName());
        wxqManagePlan.setBaseSet(Tools.getStrEmpty(JSONObject.toJSONString(wxqManagePlanDto.getBaseSet())));
        wxqManagePlan.setCreateTime(now);
        wxqManagePlan.setUpdateTime(now);

        //保存数据库
        wxqManagePlanMapper.insert(wxqManagePlan);

        //修改redis缓存
        //缓存中的微信群管理方案key
        String redisKey_manageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), wxqManagePlan.getId());
        redisTemplate.opsForValue().set(redisKey_manageplan, wxqManagePlan.getBaseSet());

        //返回到前台
        return id;
    }

    /**
     * 修改微信群管理方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqManagePlanDto
     * @return null
     */
    public void updateWxqManagePlan(WxqManagePlanDto wxqManagePlanDto){

        if(wxqManagePlanDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(wxqManagePlanDto.getName() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称不能为空");
        }

        WxqManagePlan wxqManagePlan_old = wxqManagePlanMapper.selectById(wxqManagePlanDto.getId(), wxqManagePlanDto.getMerId());
        if(wxqManagePlan_old == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该管理方案不存在");
        }

        //验证新名字是否已经存在
        if(!wxqManagePlan_old.getName().equals(wxqManagePlanDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            WxqManagePlan wxqManagePlan_name = wxqManagePlanMapper.selectByNameAndMerId(wxqManagePlanDto.getName(), wxqManagePlan_old.getMerId());
            if(wxqManagePlan_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
            }
        }

        //微信群管理方案名称
        wxqManagePlan_old.setName(wxqManagePlanDto.getName());
        //修改功能设置
        wxqManagePlan_old.setBaseSet(Tools.getStrEmpty(JSONObject.toJSONString(wxqManagePlanDto.getBaseSet())));
        //修改时间
        wxqManagePlan_old.setUpdateTime(DateUtil.getNowTime());
        //保存数据库
        wxqManagePlanMapper.updateByIdSelective(wxqManagePlan_old);

        //修改redis缓存
        //缓存中的微信群管理方案key
        String redisKey_manageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), wxqManagePlan_old.getId());
        redisTemplate.opsForValue().set(redisKey_manageplan, wxqManagePlan_old.getBaseSet());

    }

    /**
     * 重名名
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqManagePlanDto
     * @return null
     */
    public void updateName(WxqManagePlanDto wxqManagePlanDto){
        if(wxqManagePlanDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(wxqManagePlanDto.getName() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称不能为空");
        }

        WxqManagePlan wxqManagePlan_old = wxqManagePlanMapper.selectById(wxqManagePlanDto.getId(), wxqManagePlanDto.getMerId());
        if(wxqManagePlan_old == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该管理方案不存在");
        }

        //验证新名字是否已经存在
        if(!wxqManagePlan_old.getName().equals(wxqManagePlanDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            WxqManagePlan wxqManagePlan_name = wxqManagePlanMapper.selectByNameAndMerId(wxqManagePlanDto.getName(), wxqManagePlan_old.getMerId());
            if(wxqManagePlan_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
            }
        }

        //微信群管理方案名称
        wxqManagePlan_old.setName(wxqManagePlanDto.getName());

        //修改时间
        wxqManagePlan_old.setUpdateTime(DateUtil.getNowTime());

        //保存数据库
        wxqManagePlanMapper.updateByIdSelective(wxqManagePlan_old);
    }

    /**
     * 删除微信群管理方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqManagePlanIdDto
     * @return null
     */
    @Transactional
    public void deleteWxqManagePlan(WxqManagePlanIdDto wxqManagePlanIdDto){

        if(wxqManagePlanIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //将微信群管理方案查询出来
        WxqManagePlan wxqManagePlan =  wxqManagePlanMapper.selectById(wxqManagePlanIdDto.getId(), wxqManagePlanIdDto.getMerId());
        if(wxqManagePlan == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群管理方案不存在");
        }

        //是否已经用了
        WxGroupQuery wxGroupQuery = new WxGroupQuery();
        wxGroupQuery.setMerId(wxqManagePlanIdDto.getMerId());
        wxGroupQuery.setManagePlanId(wxqManagePlanIdDto.getId());
        wxGroupQuery.setCurrent(1);
        wxGroupQuery.setSize(5);
        wxGroupQuery.setUserType(1);//查询微信群
        Page<WxGroupInfoVo> wxGroupInfoVoPage = wxGroupService.findWxGroupList(wxGroupQuery);
        if(wxGroupInfoVoPage != null && wxGroupInfoVoPage.getTotal() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此管理方案已经有群在使用，不能删除");
        }

        //验证此时数量是否时最后一个，如果是最后一个，则不能删除
        WxqManagePlanQuery wxqManagePlanQuery = new WxqManagePlanQuery();
        wxqManagePlanQuery.setMerId(wxqManagePlanIdDto.getMerId());
        List<WxqManagePlan> wxqManagePlanList = wxqManagePlanMapper.findByList(wxqManagePlanQuery);

        if(wxqManagePlanList == null || wxqManagePlanList.size() <= 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最后一个管理方案不能删除");
        }
        //删除微信群管理方案数据
        wxqManagePlanMapper.deleteById(wxqManagePlanIdDto.getId(), wxqManagePlanIdDto.getMerId());

        //删除redis缓存
        //缓存中的微信群管理方案key
        String redisKey_manageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), wxqManagePlanIdDto.getId());
        redisTemplate.delete(redisKey_manageplan);

    }


//    分割线---------

    /**
     * Cv
     *
     * @param param
     * @return
     */
    @Override
    public SysPluginVo findSysPluginInfo(ConfigPlanPluginIdDto param) {
        if(param.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SysPlugin sysPlugin = sysPluginMapper.selectById(param.getId(), param.getMerId());
        if(sysPlugin == null){
            sysPlugin = new SysPlugin();
        }
        //返回给页面的对象
        SysPluginVo sysPluginVo = new SysPluginVo();
        BeanUtils.copyProperties(sysPlugin, sysPluginVo);
        return  sysPluginVo;
    }

    /**
     * Cv
     *
     * @param param
     * @return
     */
    @Override
    public Long updateSysPlugin(ConfigPlanPluginUpdateDto param) {
        if (param.getConfigPlanID() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        if (StringUtils.isBlank(param.getPlugName()) || StringUtils.isBlank(param.getData())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //页面传过来的是驼峰型，末尾是Id的后缀去掉末尾Id
        String plugName_hump = param.getPlugName().replaceAll("Id", "");
        //驼峰型转成下划线型
        String plugName = Tools.humpToLine(plugName_hump);

        //查询配置方案
        ConfigPlan exisctsConfigPlan = configPlanMapper.selectById(param.getConfigPlanID(), param.getMerId());
        if (exisctsConfigPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        Integer now = DateUtil.getNowTime();
        Long id = IdWorker.getId();
        //返回到页面用

        SysPlugin needSaveSysPlugin = new SysPlugin();
        needSaveSysPlugin.setId(id);
        needSaveSysPlugin.setMerId(param.getMerId());
        needSaveSysPlugin.setPlugName(plugName);
        needSaveSysPlugin.setData(param.getData());
        needSaveSysPlugin.setCreateTime(now);
        needSaveSysPlugin.setUpdateTime(now);
        sysPluginMapper.insert(needSaveSysPlugin);

        //插件ID存在，则修改
        if (param.getId() != null) {
            // 删除老的配件
            sysPluginMapper.deleteById(param.getId(), param.getMerId());
            redisTemplate.delete(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), param.getId()));
        }
        param.setId(id);
        // 设置配置方案中的ID
        ReflectUtil.setFieldValue(exisctsConfigPlan, param.getPlugName(), id);
        // 更新
        configPlanMapper.update(exisctsConfigPlan);

        // 缓存
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), needSaveSysPlugin.getId()), needSaveSysPlugin.getData(), 5, TimeUnit.DAYS);

        return param.getId();
    }
}
